package com.trip.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.time.*;

/**
 * Return UTC timestamp
 */
@Configuration
public class JsonDateConfiguration {

    private static final ObjectMapper mapper;

    @Bean
    public ObjectMapper getMapper() {
        return mapper;
    }

    static {

        mapper = new ObjectMapper();

        SimpleModule module = new SimpleModule();
        module.addSerializer(LocalDate.class, new LocalDateSerializer());
        module.addSerializer(LocalTime.class, new LocalTimeSerializer());
        module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        mapper.registerModule(module);
    }

    static class LocalDateSerializer extends JsonSerializer<LocalDate> {


        @Override
        public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException {
            long s = value.atStartOfDay().atZone(ZoneId.of("UTC")).toInstant().getEpochSecond();
            jgen.writeString(String.valueOf(s));
        }
    }

    static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {


        @Override
        public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException {
            //ZonedDateTime utc=ZonedDateTime.from(value);
            long s = value.atZone(ZoneId.of("UTC")).toInstant().getEpochSecond();
            jgen.writeString(String.valueOf(s));
        }

    }

    static class LocalTimeSerializer extends JsonSerializer<LocalTime> {


        @Override
        public void serialize(LocalTime value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException {
            ZonedDateTime utc = ZonedDateTime.from(value);

            jgen.writeString(String.valueOf(utc.toInstant().getEpochSecond()));

        }

    }

}

